<template>
  <div class="dish-container">
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索菜品"
        prefix-icon="Search"
        clearable
        @input="handleSearch"
      />
    </div>

    <div class="dish-list">
      <el-empty v-if="!loading && dishList.length === 0" description="暂无菜品数据"></el-empty>
      <el-row v-else :gutter="20" v-loading="loading" element-loading-text="加载中...">
        <el-col :span="6" v-for="dish in dishList" :key="dish.id">
          <el-card class="dish-card">
            <div class="dish-image-container">
              <el-image
                v-if="dish.image"
                :src="dish.image"
                :preview-src-list="[dish.image]"
                fit="cover"
                class="dish-image"
              />
              <div v-else class="no-image">
                <el-icon><Picture /></el-icon>
                <span>暂无图片</span>
              </div>
            </div>
            <div class="dish-info">
              <h3>{{ dish.name }}</h3>
              <p class="dish-description">{{ dish.description }}</p>
              <div class="dish-price-action">
                <span class="dish-price">¥{{ dish.price }}</span>
                <div class="dish-action">
                  <el-button
                    type="primary"
                    size="small"
                    circle
                    @click="decreaseQuantity(dish)"
                    :disabled="!getCartQuantity(dish.id)"
                  >
                    <el-icon><Minus /></el-icon>
                  </el-button>
                  <span class="dish-quantity">{{ getCartQuantity(dish.id) }}</span>
                  <el-button
                    type="primary"
                    size="small"
                    circle
                    @click="increaseQuantity(dish)"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页控件 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 12, 16, 24]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <div class="cart-container" v-if="cartItems.length > 0">
      <div class="cart-header">
        <div class="cart-title">
          <el-icon><ShoppingCart /></el-icon>
          <span>购物车</span>
        </div>
        <el-button type="text" @click="clearCart">清空购物车</el-button>
      </div>
      <div class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <div class="item-info">
            <span class="item-name">{{ item.name }}</span>
            <span class="item-price">¥{{ item.price }}</span>
          </div>
          <div class="item-action">
            <el-button
              type="primary"
              size="small"
              circle
              @click="decreaseQuantity(item)"
            >
              <el-icon><Minus /></el-icon>
            </el-button>
            <span class="item-quantity">{{ item.quantity }}</span>
            <el-button
              type="primary"
              size="small"
              circle
              @click="increaseQuantity(item)"
            >
              <el-icon><Plus /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <div class="cart-footer">
        <div class="cart-total">
          <span>合计：</span>
          <span class="total-price">¥{{ totalPrice }}</span>
        </div>
        <el-button type="primary" @click="checkout">去结算</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, ShoppingCart, Plus, Minus, Picture } from '@element-plus/icons-vue'
import { dishApi, orderApi } from '../../api/index'

const router = useRouter()
const searchKeyword = ref('')
const loading = ref(false)

// 菜品列表
const dishList = ref<any[]>([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 购物车
const cartItems = ref<any[]>([])

// 加载所有菜品
const loadDishes = async () => {
  loading.value = true
  try {
    const res = await dishApi.page({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    dishList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error: any) {
    ElMessage.error(error.message || '获取菜品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索菜品
const handleSearch = async () => {
  currentPage.value = 1 // 搜索时重置为第一页
  loadFilteredDishes()
}

// 加载筛选后的菜品
const loadFilteredDishes = async () => {
  loading.value = true
  try {
    let res
    if (searchKeyword.value.trim()) {
      res = await dishApi.search({
        page: currentPage.value,
        pageSize: pageSize.value,
        name: searchKeyword.value
      })
    } else {
      res = await dishApi.page({
        page: currentPage.value,
        pageSize: pageSize.value
      })
    }

    // 分页接口返回的数据结构是 {records: [...], total: number}
    dishList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error: any) {
    ElMessage.error(error.message || '获取菜品失败')
  } finally {
    loading.value = false
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadFilteredDishes()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadFilteredDishes()
}

// 获取购物车中菜品数量
const getCartQuantity = (dishId: number) => {
  const item = cartItems.value.find(item => item.id === dishId)
  return item ? item.quantity : 0
}

// 增加菜品数量
const increaseQuantity = (dish: any) => {
  const item = cartItems.value.find(item => item.id === dish.id)
  if (item) {
    item.quantity++
  } else {
    cartItems.value.push({
      id: dish.id,
      name: dish.name,
      price: dish.price,
      quantity: 1
    })
  }
}

// 减少菜品数量
const decreaseQuantity = (dish: any) => {
  const index = cartItems.value.findIndex(item => item.id === dish.id)
  if (index !== -1) {
    if (cartItems.value[index].quantity > 1) {
      cartItems.value[index].quantity--
    } else {
      cartItems.value.splice(index, 1)
    }
  }
}

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cartItems.value = []
    ElMessage.success('购物车已清空')
  }).catch(() => {})
}

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// 结算
const checkout = () => {
  if (!localStorage.getItem('user')) {
    ElMessageBox.confirm('请先登录后再结算', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/login')
    }).catch(() => {})
    return
  }

  // 显示订单确认对话框
  const orderItems = cartItems.value.map(item => ({
    dishId: item.id,
    dishName: item.name,
    price: item.price,
    number: item.quantity,
    amount: item.price * item.quantity
  }))

  const totalAmount = totalPrice.value

  // 获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}')

  // 构建订单确认内容
  let confirmContent = `<div style="max-height: 300px; overflow-y: auto;">
    <h3>订单详情</h3>
    <div style="margin-bottom: 15px;">
      <table style="width: 100%; border-collapse: collapse;">
        <thead>
          <tr style="border-bottom: 1px solid #eee;">
            <th style="text-align: left; padding: 8px;">菜品</th>
            <th style="text-align: right; padding: 8px;">单价</th>
            <th style="text-align: right; padding: 8px;">数量</th>
            <th style="text-align: right; padding: 8px;">小计</th>
          </tr>
        </thead>
        <tbody>`

  orderItems.forEach(item => {
    confirmContent += `
      <tr style="border-bottom: 1px solid #eee;">
        <td style="text-align: left; padding: 8px;">${item.dishName}</td>
        <td style="text-align: right; padding: 8px;">¥${item.price}</td>
        <td style="text-align: right; padding: 8px;">${item.number}</td>
        <td style="text-align: right; padding: 8px;">¥${item.price * item.number}</td>
      </tr>`
  })

  confirmContent += `
        </tbody>
      </table>
    </div>
    <div style="text-align: right; font-weight: bold; margin-top: 10px;">
      总计: <span style="color: #f56c6c; font-size: 18px;">¥${totalAmount}</span>
    </div>
  </div>`

  ElMessageBox.confirm(confirmContent, '确认订单', {
    confirmButtonText: '提交订单',
    cancelButtonText: '取消',
    dangerouslyUseHTMLString: true,
    center: true
  }).then(async () => {
    try {
      // 构建订单数据
      const orderData = {
        // 用户信息
        userId: userInfo.id,
        userName: userInfo.name || '用户',
        phone: userInfo.phone || '',
        address: userInfo.address || '',

        // 订单信息
        amount: totalAmount,
        remark: '',

        // 订单项
        orderDetails: orderItems
      }

      // 调用提交订单API
      const loading = ElLoading.service({
        lock: true,
        text: '订单提交中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const res = await orderApi.submitOrder(orderData)
        loading.close()

        ElMessage.success('订单提交成功')

        // 清空购物车
        cartItems.value = []

        // 跳转到订单页面
        router.push('/user/order')
      } catch (error: any) {
        loading.close()
        ElMessage.error(error.message || '订单提交失败，请稍后再试')
      }
    } catch (error: any) {
      ElMessage.error(error.message || '订单提交失败，请稍后再试')
    }
  }).catch(() => {
    // 用户取消订单确认
  })
}

// 组件挂载时加载菜品数据
onMounted(() => {
  loadFilteredDishes()
})
</script>

<style scoped>
.dish-container {
  padding: 20px;
  position: relative;
}

.search-bar {
  margin-bottom: 20px;
}

.dish-list {
  margin-bottom: 80px;
}

.dish-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
}

.dish-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.dish-image-container {
  width: 100%;
  height: 200px;
  overflow: hidden;
  position: relative;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #c0c4cc;
  font-size: 14px;
}

.no-image .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
}

.dish-info {
  padding: 15px;
}

.dish-info h3 {
  margin-top: 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.dish-description {
  color: #666;
  margin: 12px 0;
  min-height: 40px;
  line-height: 1.5;
  overflow: hidden;
}

.dish-price-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dish-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.dish-action {
  display: flex;
  align-items: center;
}

.dish-quantity {
  margin: 0 10px;
  width: 20px;
  text-align: center;
}

.cart-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #eee;
}

.cart-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.cart-title .el-icon {
  margin-right: 5px;
  font-size: 20px;
}

.cart-items {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px 20px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.item-info {
  display: flex;
  justify-content: space-between;
  width: 200px;
}

.item-name {
  font-weight: bold;
}

.item-price {
  color: #f56c6c;
}

.item-action {
  display: flex;
  align-items: center;
}

.item-quantity {
  margin: 0 10px;
  width: 20px;
  text-align: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-top: 1px solid #eee;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.pagination {
  margin: 30px 0;
  display: flex;
  justify-content: flex-end;
}
</style>